import inspect
from datetime import datetime
from os.path import join

from mg_app_framework import get_store, update_context, get_logger, get_context


def fullname(o):
    module = inspect.getmodule(o)
    return f"{module.__name__}.{o.__qualname__}"


def now_time_string() -> str:
    now_time = datetime.now()
    return datetime_to_sting(now_time)


def datetime_to_sting(dt: datetime, dt_format: str = "%Y-%m-%d %H:%M:%S") -> str:
    return dt.strftime(dt_format)


def string_to_datetime(st_dt: str, dt_format: str = "%Y-%m-%d %H:%M:%S") -> datetime:
    return datetime.strptime(st_dt, dt_format)


def format_seconds_to_hms_str(seconds, to_excel=False):
    """
    fix: 如果传入时间为负数或者为空,默认给0值
    传入一个整型的秒数，格式化成"t天h时m分s秒"的字符串
    :param seconds: int
    :param to_excel: bool，是否提供数据给excel导出使用
    :return: t天h时m分s秒: str
    """
    if not seconds or seconds < 0:
        seconds = 0
    if not to_excel:
        t = seconds // (60 * 60 * 24)
        h = (seconds - t * 60 * 60 * 24) // (60 * 60)
        m = (seconds - t * 60 * 60 * 24 - h * 60 * 60) // 60
        s = seconds - t * 60 * 60 * 24 - h * 60 * 60 - m * 60
        return "{}{}{}{}".format(
            "{:.0f}天".format(t) if t != 0 else "",
            "{:.0f}时".format(h) if t != 0 or h != 0 else "",
            "{:.0f}分".format(m) if t != 0 or h != 0 or m != 0 else "",
            "{:.0f}秒".format(s),
        )
    else:
        return round(seconds / 60, 2)


def format_validation_error(errors):
    return ";".join([f"{'.'.join(error['loc'])}: {error['msg']}" for error in errors])


class ToExcelFile:
    def __init__(self, file_name: str):
        if file_name is None:
            file_name = '报表导出'
        if file_name and not file_name.endswith('.xls'):
            file_name = '{}.xls'.format(file_name)
        self.file_name = file_name

    def xls_save_path(self, default_path=None):
        work_dir = get_store().get_module_dir()
        if default_path:
            excel_path = join(work_dir, default_path, self.file_name)
        else:
            excel_path = join(work_dir, self.file_name)
        return excel_path


def mq_update_context_help(context_key: str, context_val):
    update_context(context_key, context_val)
    get_logger().info("mq update context suc, key:{}, value:{}".format(
        context_key, get_context(context_key)
    ))
